package com.loginCheck.servlet;

import com.loginCheck.pojo.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/loginCheckServlet")
public class LoginCheckServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //获取请求数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        //创建user对象
        User user = new User();
        user.setId(1);
        user.setUsername("张三");
        user.setPassword("123");

        //进行判断获取的数据和user对象中的是否一致
        if (user.getUsername().equals(username) && user.getPassword().equals(password)) {
            System.out.println("登录成功。");
            //将user对象存储到域中
            request.getSession().setAttribute("user", user);

            //一致跳转到成功页面(使用重定向)
            String path = request.getContextPath();
            System.out.println("path结果为: " + path);

            //使用path灵活配置路径
            response.sendRedirect(path + "/jsp/success.jsp");
        } else {
            //不一致跳转到登录页面
            System.out.println("密码错误！请重新输入密码");
            //向域中存储message数据
            request.setAttribute("message", "用户名或密码错误！请重新输入。");
            //转发到登录页面
            request.getRequestDispatcher("/jsp/login.jsp").forward(request, response);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
